<?php

namespace app\common\library\xiluhouse;

use EasyWeChat\Factory;
use fast\Http;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Exception;
use think\exception\ErrorException;

class Wxmini
{
    private $app;
    public $payment;

    public function __construct()
    {
        $config = get_addon_config('xiluhouse');
        $options = [
            'app_id'      => $config['AppID'],
            'secret'      =>  $config['AppSecret'],
            'response_type' => 'array',
        ];

        $payment_config = [
            // 必要配置
            'app_id'             => $config['AppID'] ?? '',
            'mch_id'             => $config['mch_id'],
            'key'                => $config['mch_key'],   // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => '', // XXX: 绝对路径！！！！
            'key_path'           => '',      // XXX: 绝对路径！！！！
            'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它
        ];

        try {
            $this->app = Factory::miniProgram($options);
            $this->payment = Factory::payment($payment_config);
        } catch (\Exception $e) {
            \think\Log::error('初始化失败：' . $e->getMessage());
        }
    }
    /**
     * 根据 jsCode 获取用户 session 信息
     */
    public function jscode2session($code)
    {
        return $this->app->auth->session($code);
    }

    /**
     * 获取手机号
     * @param $code
     */
    public function getPhoneNumber($code){
        $token = $this->app->access_token->getToken();

        try {
            $data = Http::post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token['access_token'],json_encode(['code'=>$code]));
            $data = json_decode($data,true);
            if($data['errcode'] != '0'){
                throw new Exception("获取手机号失败");
            }
        }catch (ErrorException $exception){
            throw $exception;
        }


        return $data['phone_info'];
    }

    /**
     * 微信小程序消息解密
     */
    public function decryptData($session, $iv, $encryptedData)
    {
        return $this->app->encryptor->decryptData($session, $iv, $encryptedData);
    }
    /**
     * 敏感词验证
     */
    public function checkContent($content)
    {
        $check_result = $this->app->content_security->checkText($content);
        if ($check_result['errcode'] != 0) {
            $check_result['errmsg'] = '敏感词验证不通过';
        }
        return $check_result;
    }
    /**
     * 图片验证
     */
    public function checkMedia($filePath)
    {
        $check_result = $this->app->content_security->checkImage($filePath);
        if ($check_result['errcode'] != 0) {
            $check_result['errmsg'] = '敏感图片验证不通过';
        }
        return $check_result;
    }
    //生成小程序二维码
    public function getWXacode($scene = 'code', $page = 'pages/home/index/index', $info = [])
    {
        $app     = $this->app;
        $response = $app->app_code->getUnlimit($scene, [
            'page'  => $page,
            'width' => 600,
        ]);
        $resfilename = '';
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $resfilename = $response->getBodyContents();
        }
        return $resfilename;


        $filename = md5(mt_rand());
        $name = $filename . ".png";
        $md5 = md5(mt_rand(10000, 99999));
        $auth = new \addons\alioss\library\Auth();
        $params = $auth->params($name, $md5, false);

        $savekey = '/' . $params['key'];
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        $path = "/uploads" . $uploadDir;
        if (!file_exists('.' . $path)) {
            mkdir('.' . $path, 0777, true);
        }

        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $response->saveAs('.' . $path, $fileName);
        }
        $filePath = ROOT_PATH . '/public' . $path . $fileName;

        $uploadconfig = \think\Config::get('upload');
        if ($uploadconfig['storage'] == 'alioss') {
            try {
                $config = get_addon_config('alioss');
                $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], "http://" . $config['endpoint']);
                $ossClient->uploadFile($config['bucket'], $params['key'], $filePath);
            } catch (OssException $e) {
                @unlink($filePath);
                \think\Log::error('上传失败:' . $e->getMessage());
                return '';
            }
            @unlink($filePath);
        }

        return $savekey;
    }


    /**
     * 生成统一订单
     */
    public function union_order($order){

        $orderinfo = [
            'body'              => $order['body'],
            'out_trade_no'      => $order['order_no'],
            'total_fee'         => (int)($order['pay_price'] * 100),
            //'spbill_create_ip'  => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url'        => $order['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type'        => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid'            => $order['openid'],
        ];
        try {
            $wxpay = $this->payment->order->unify($orderinfo);
            if($wxpay['return_code'] == "FAIL" || $wxpay['result_code'] == "FAIL"){
                throw new Exception($wxpay['return_code'] == "FAIL"?$wxpay['return_msg']:$wxpay['err_code_des']);
            }
            $wxconfig = $this->payment->jssdk->bridgeConfig($wxpay['prepay_id'], false);
        }catch (Exception $e){
            throw $e;
        }
        return $wxconfig;
    }
}
